import { fuzzyQueryEnterprises } from '@/services/zhirong/enterprise';
import { useRequest } from '@umijs/hooks';
import { Button, message, Select, Space, Tag, Spin } from 'antd';
import { useEffect, useState } from 'react';
import { nanoid } from 'nanoid';
import { KeepAlive } from 'umi'
import { set } from 'lodash';
const { Option } = Select;

const SearchInput = (props) => {
  // 模糊查询得到的企业列表状态
  const [enterpriseList, setEnterpriseList] = useState([]);
  // 从列表中选定的企业状态
  const [enterprise, setEnterprise] = useState({
    name: null,
    eid: '',
    status: '',
  });
  const [comName, setComName] = useState('');
  useEffect(() => {
    if (props.forceSet && props.forceSet.eid && props.forceSet.FullName) {
      setEnterpriseList([props.forceSet]);
      setEnterprise(props.forceSet);
      // setQuery(props.forceSet.FullName);
      setComName(props.forceSet.FullName);
    }
  }, [props.forceSet]);

  useEffect(() => {

    if (enterprise.eid) {

      props.onSelect(enterprise);
    }
  }, [enterprise]);
  // 输入的查询词状态，用于在下拉列表中进行高亮显示
  const [query, setQuery] = useState('');
  // 使用防抖的异步请求hook进行模糊查询
  const { loading, run } = useRequest(fuzzyQueryEnterprises, {
    debounceInterval: 800,
    manual: true,
    onSuccess: (result, params) => {
      console.log('搜索结果，', result);
      if (result && result.code === 200) {
        if (result.data)
          setEnterpriseList(result.data);
      } else {
        console.log('msg:', result.msg);
      }
      console.log('loading:', loading);
    },
    onError: (err, params) => {
      console.log('err:', err);
      message.error('查询错误');
    },
  });
  // select框输入行为所触发的函数，发送异步请求获取企业列表
  const handleSearch = (queryWords) => {
    console.log('搜索：', queryWords);
    if (queryWords && queryWords.length >= 1) {
      setQuery(queryWords);
      run({
        company_name: queryWords,
        // limit: 5,
        // ts: new Date().getTime(),
      });
    } else {
      setEnterpriseList([]);
    }
  };

  // select框失去焦点保证输入的值还在
  const handleBlur = (eid) => {

    setEnterprise({ name: query });
  }
  // const handleKey = (key) => {
  //    if(key.keyCode === 13){
  //      console.log("query",query);
  //      console.log("an enter");
  //     //  setEnterprise({name:query});
  //     return false;
  //    }

  // }
  // select下拉列表选择企业所触发的函数，确定目标企业更新选定企业状态并更新查询词为目标企业名
  const handleChange = (eid) => {

    console.log('改变', eid);
    //  debugger
    let [target] = enterpriseList.filter((item) => item.FullName === eid);

    setEnterprise(target);
    setComName(target.FullName);
    props.onSelect(target);

    // setQuery(target.FullName);
  };
  // 用于生成包含高亮的查询关键词的候选企业列表条目
  const hightlightQuery = (name) => {
    if (name) {
      const startIndex = name.indexOf(query);
      const queryLength = query.length;
      // console.log(name,query, name.slice(0, startIndex))
      return (
        <>
          {startIndex === -1 ? (
            <span>{name}</span>
          ) : (
            <span>
              {name.slice(0, startIndex)}
              <span style={{ color: 'red' }}>{name.substr(startIndex, queryLength)}</span>
              {name.slice(startIndex + queryLength)}
            </span>
          )}
        </>
      );
    }


  };

  const options = enterpriseList.map((item) => (
    <Option key={item.FullName}>
      <Space>
        {hightlightQuery(item.FullName)}
        {item.Status === '存续（在营、开业、在册）' && <Tag color="blue">存续</Tag>}
        {item.Status === '注销' && <Tag color="orange">注销</Tag>}
        {item.Status === '迁出' && <Tag color="orange">迁出</Tag>}
        {String(item.Status).indexOf('吊销') !== -1 && <Tag color="red">吊销</Tag>}
      </Space>
    </Option>
  ));
  return (
    <Space>
      <Select
        showSearch
        showArrow={false}
        value={comName == '' ? null : comName}
        placeholder={props.placeholder}
        style={props.style}
        defaultActiveFirstOption={false}
        filterOption={false}
        onSearch={handleSearch}
        onSelect={handleChange}
        // onBlur={handleBlur}
        notFoundContent={loading ? <Spin size="small" tip="搜索中" /> : null}
      >
        {options}
      </Select>
    </Space>
  );
};

const SearchBox = (props) => {
  const [enterprise, setEnterprise] = useState({
    name: null,
    eid: '',
    status: '',
  });
  const [forceSet, setForceSet] = useState();
  // 点击查询button触发时无item参数 点击排行榜列表title触发时有item参数
  const handleClick = (item = undefined) => {
    if (item) {
      const res = item.eid ? item : enterprise;
      props.onSubmit(res);
    } else {
      props.onSubmit(enterprise);
    }

  };

  const handleSelected = (value) => {
    console.log("aaaa", value)
    //debugger
    setEnterprise({ ...value });
  };




  return (
    <KeepAlive>
      <Space direction="vertical" align="start" >
        <Space>
          <SearchInput
            forceSet={forceSet}
            onSelect={handleSelected}
            placeholder={props.value ? props.value : '请输入您要查询的企业名称'}
            style={{ width: 500 }}
          />
          <Button type="primary" onClick={handleClick} htmlType="submit">
            查询
          </Button>
        </Space>

        <Space style={{ color: '#999999' }} >
          搜索建议:
          {props.advices?.map((advice) => (
            <Button
              key={nanoid()}
              onClick={() => {
                props.onSubmit(advice);
                setForceSet(advice);
              }}
              style={{ backgroundColor: '#F7F7F7', color: '#999999' }}
            >
              {advice.FullName}
            </Button>
          ))}
        </Space>
      </Space>
    </KeepAlive>
  );
};

export default SearchBox;
